package com.usian.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.usian.admin.mapper.AdChannelMapper;
import com.usian.admin.service.AdChannelService;
import com.usian.model.admin.dtos.ChannelDto;
import com.usian.model.admin.pojos.AdChannel;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class AdChannelServiceImpl implements AdChannelService {
    @Autowired
    private AdChannelMapper adChannelMapper;
    @Override
    public ResponseResult findByNameAndPage(ChannelDto dto) {
        if (dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        Page page = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<AdChannel> qw = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(dto.getName())){
            qw.like(AdChannel::getName,dto.getName());
        }
//        if (dto.getStatus()!=null){
//            qw.eq(AdChannel::getStatus,dto.getStatus());
//        }
        Page page1 = adChannelMapper.selectPage(page, qw);
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page1.getTotal());
        responseResult.setData(page1.getRecords());
        return responseResult;
    }

    @Override
    public ResponseResult save(AdChannel adChannel) {
//        检查参数
        if (adChannel ==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
//       保存参数
        adChannel.setCreatedTime(new Date());
        adChannelMapper.insert(adChannel);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult update(AdChannel adChannel) {
        if (adChannel ==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        adChannelMapper.updateById(adChannel);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
    @Override
    public ResponseResult deleteById(Integer id) {
        if (id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
//        判断当前频道是否存在和有效
        AdChannel adChannel = adChannelMapper.selectById(id);
        if (adChannel==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        adChannelMapper.deleteById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
